import util from 'jax-base/utils/util'
import { getToken, setToken, removeToken } from 'jax-base/utils/auth'
import adminApi from './api/admin'
import config from '@/config'
import router from '@/router'

const PCE = 0 // 电脑展开
const PCN = 1 // 电脑合并
const PHE = 2 // 手机展开
const PHN = 3 // 手机合并

let sizeType
if (document.body.offsetWidth > 1024) {
  sizeType = 'PC'
} else if (document.body.offsetWidth > 768) {
  sizeType = 'PAD'
} else {
  sizeType = 'PHONE'
}

const adminAtore = {
  namespaced: true,
  state() {
    return {
      token: getToken(),

      // 系统配置
      config: {},

      // 用户信息
      userInfo: {},

      // 词典
      dict: {},

      // 菜单栏
      menuBar: {
        // 大小类型 PC（1024）、PAD（768）、PHONE（768以下）
        sizeType,

        status: document.body.offsetWidth < 768 ? PHN : PCE,

        // 菜单列表
        menuList: [],

        // 菜单树（菜单列表的一维对象）
        menuTree: {},

        isPhone: document.body.offsetWidth < 768,

        // 已打开菜单
        openMenuList: [],

        // 缓存的菜单(标签切换时使用缓存)
        cacheMenuPath: {},
      },

      // 标签栏
      tabBar: {
        tabList: [],
        cachedViews: [],
      },
    }
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
    },

    SET_USER_INFO(state, data) {
      state.userInfo = data
    },

    SET_DICT(state, data) {
      state.dict = data
    },

    SET_CONFIG(state, data) {
      document.title = data.title
      state.config = data
    },

    // 获取菜单
    SET_MENU(state, data) {
      const menuTree = {}

      data = util.recurseTree(data, (item) => {
        if (item.path) {
          item.path = config.base + item.path
        }
        // 不能为空，饿了么组件需要唯一值
        else {
          item.path = item.id
        }

        menuTree[item.path] = item
      })

      state.menuBar.menuList = data
      state.menuBar.menuTree = menuTree
    },

    // 菜单切换
    CHANGE_MENU(state, options) {
      const { path, query, cache } = {
        cache: true,
        ...options,
      }

      if (cache) {
        state.menuBar.cacheMenuPath[path] = true
      } else {
        state.menuBar.cacheMenuPath[path] = false
      }

      router.push({
        path,
        query,
      })

      const menuItem = state.menuBar.menuTree[path]
      if (!menuItem) return

      const index = state.menuBar.openMenuList.findIndex((item) => item.path === menuItem.path)
      state.menuBar.openMenuList.forEach((item) => (item.isActive = false))

      // 判断页面是否打开过
      if (index !== -1) {
        state.menuBar.openMenuList[index].isActive = true
        return
      }

      state.menuBar.openMenuList.push({
        menuName: menuItem.menuName,
        path: menuItem.path,
        isActive: true,
      })
    },

    // 关闭已打开菜单
    closeOpenMenu() {},
  },
  actions: {
    // 登录
    login({ commit, dispatch }, data) {
      const username = data.username.trim()
      const password = data.password

      return adminApi
        .login({
          username,
          password,
        })
        .then((res) => {
          dispatch('loginSuccess', res)
        })
    },
    // 跳转登录
    goLogin() {
      const goUrl = `${config.base}/login?backUrl=` + encodeURIComponent(location.href)
      location.href = goUrl
    },
    // 登录成功
    loginSuccess({ commit }, user) {
      setToken(user.token)
      commit('SET_TOKEN', user.token)

      const { query } = router.currentRoute.value
      let backUrl = query.backUrl
      if (backUrl) backUrl = decodeURIComponent(backUrl)

      setTimeout(() => {
        location.href = backUrl || config.base + '/'
      }, 500)
    },

    // 退出系统
    logout({ commit, dispatch }) {
      commit('SET_TOKEN', null)
      removeToken()
      location.href = `${config.base}/login`
      // dispatch('goLogin')
    },

    // 获取用户配置
    getUserInfo({ commit }) {
      adminApi.getUserInfo().then((res) => {
        commit('SET_USER_INFO', res)
      })
    },

    // 获取词典
    getDict({ commit }) {
      adminApi.getDict().then((res) => {
        commit('SET_DICT', res)
      })
    },

    // 获取系统配置
    getConfig({ commit }) {
      adminApi.setting().then((res) => {
        commit('SET_CONFIG', res)
      })
    },

    // 获取菜单栏
    getMenu({ commit }, query) {
      adminApi.home(query).then((res) => {
        const { menuList, defaultMenu } = res
        commit('SET_MENU', menuList)

        console.log('base', config.base + '/')
        console.log('router.currentRoute.value.path', router.currentRoute.value.path)

        // 默认URL
        if ([config.base + '/'].includes(router.currentRoute.value.path)) {
          // 切换到默认路由
          if (defaultMenu) {
            console.log('切换到默认路由')
            commit('CHANGE_MENU', {
              path: config.base + defaultMenu.path,
            })
          }
        }
        // commit('changeMenu', {
        //     path: router.currentRoute.value.path,
        // });
      })
    },
  },
}

export default adminAtore
